<template>
	<el-drawer v-model="state.visible" :title="cartTitle" :size="'80%'" direction="rtl" :before-close="handleClose">
		<div class="cart-content">
			<el-empty v-if="cartItems.length === 0" :description="'购物车为空，请选择需要' + (cartType === 'inbound' ? '入库' : '出库') + '的物资'">
				<el-button type="primary" @click="handleClose">去选择物资</el-button>
			</el-empty>

			<div v-else>
				<!-- 顶部全局设置区域 -->
				<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
					<el-form :model="state.globalForm" labelWidth="90">
						<el-row>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" class="mb10">
								<el-form-item label="接收人">
									<el-select v-model="state.globalForm.receiverId" placeholder="选择接收人" filterable clearable @change="handleGlobalReceiverChange">
										<el-option v-for="user in userOptions" :key="user.id" :label="user.realName" :value="user.id">
											<span style="float: left">{{ user.realName }}</span>
											<span style="float: right; color: #8492a6; font-size: 13px">
												{{ user.orgName }}
											</span>
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
								<el-form-item label="预期时间">
									<el-date-picker v-model="state.globalForm.expectedDate" type="datetime" placeholder="请选择预期时间" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
								<el-form-item label="状态类型">
									<g-sys-dict v-model="state.globalForm.statusNewOrChange" code="StatusNewOrChangeEnum" render-as="select" placeholder="请选择状态类型" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" class="mb10">
								<el-form-item label="确认人">
									<div class="confirmer-input-wrapper">
										<el-select 
											v-model="state.globalForm.confirmerId" 
											placeholder="选择确认人(可空)" 
											filterable 
											clearable 
											:disabled="state.confirmerReadonly" 
											@change="handleConfirmerChange"
											class="confirmer-select"
										>
											<el-option v-for="user in userOptions" :key="user.id" :label="user.realName" :value="user.id">
												<span style="float: left">{{ user.realName }}</span>
												<span style="float: right; color: #8492a6; font-size: 13px">
													{{ user.orgName }}
												</span>
											</el-option>
										</el-select>
										<el-button 
											:type="state.confirmerReadonly ? 'primary' : 'default'" 
											:icon="state.confirmerReadonly ? 'ele-Edit' : 'ele-Lock'" 
											@click="toggleConfirmerReadonly"
											:title="state.confirmerReadonly ? '点击编辑确认人' : '点击锁定确认人'"
											class="confirmer-toggle-btn"
										>
											{{ state.confirmerReadonly ? '编辑' : '锁定' }}
										</el-button>
									</div>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" class="mb10">
								<el-form-item>
									<el-button-group style="display: flex; align-items: center">
										<el-button type="primary" icon="ele-Check" @click="applyGlobalSettings">应用全局</el-button>
										<el-button type="danger" icon="ele-Delete" @click="clearCart" :disabled="cartItems.length === 0">清空购物车</el-button>
										<el-button type="success" icon="ele-ShoppingCart" :disabled="true"> {{ cartItems.length }}种物资 | {{ totalQuantity }}件 | ¥{{ totalAmount.toFixed(2) }} </el-button>
									</el-button-group>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-card>

				<!-- 购物车表格 -->
				<el-card class="full-table" shadow="hover" style="margin-top: 5px">
					<el-table :data="cartItems" style="width: 100%" tooltip-effect="light" row-key="id" border>
						<el-table-column type="index" label="序号" width="55" align="center" fixed="left" />
						<el-table-column prop="storeTypeDisplayName" label="分类" width="120" fixed="left" show-overflow-tooltip />
						<el-table-column prop="name" label="物资名秴" width="200" fixed="left" show-overflow-tooltip />
						<el-table-column prop="unit" label="单位" width="80" show-overflow-tooltip />
						<el-table-column prop="price" label="单价" width="100" show-overflow-tooltip>
							<template #default="scope">
								<span class="price-text">¥{{ scope.row.price }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="availableStock" label="可用库存" width="100" show-overflow-tooltip />
						<el-table-column label="申请数量" width="120" align="center">
							<template #default="scope">
								<el-input-number 
									v-model="scope.row.requestQuantity" 
									:min="1" 
									:max="cartType === 'outbound' ? scope.row.availableStock : undefined" 
									size="small" 
									@change="updateItemTotal(scope.row)" 
								/>
							</template>
						</el-table-column>
						<el-table-column label="小计" width="100" align="center">
							<template #default="scope">
								<span class="total-price">¥{{ (scope.row.price * scope.row.requestQuantity).toFixed(2) }}</span>
							</template>
						</el-table-column>
						<el-table-column label="接收人" width="180">
							<template #default="scope">
								<el-select
									:model-value="scope.row.receiverId"
									placeholder="选择接收人"
									size="small"
									filterable
									clearable
									@change="(value: number) => handleItemReceiverChange(scope.row, value)"
									style="width: 100%"
								>
									<el-option v-for="user in userOptions" :key="user.id" :label="user.realName" :value="user.id">
										<span style="float: left">{{ user.realName }}</span>
										<span style="float: right; color: #8492a6; font-size: 11px">
											{{ user.orgName }}
										</span>
									</el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="预期时间" width="180">
							<template #default="scope">
								<el-date-picker v-model="scope.row.expectedDate" type="datetime" placeholder="预期时间" value-format="YYYY-MM-DD HH:mm:ss" size="small" style="width: 100%" />
							</template>
						</el-table-column>
						<el-table-column label="状态类型" width="120">
							<template #default="scope">
								<g-sys-dict v-model="scope.row.statusNewOrChange" code="StatusNewOrChangeEnum" render-as="select" placeholder="状态" size="small" />
							</template>
						</el-table-column>
						<el-table-column label="备注" width="150">
							<template #default="scope">
								<el-input v-model="scope.row.remark" placeholder="备注" size="small" clearable />
							</template>
						</el-table-column>
						<el-table-column label="操作" width="80" align="center" fixed="right">
							<template #default="scope">
								<el-button type="danger" size="small" text :icon="Delete" @click="removeFromCart(scope.$index)">移除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-card>
			</div>
		</div>

		<template #footer>
			<div class="cart-footer">
				<div class="footer-summary">
					<span>共 {{ cartItems.length }} 种物资，{{ totalQuantity }} 件，总计 ¥{{ totalAmount.toFixed(2) }}</span>
				</div>
				<div class="footer-actions">
					<el-button @click="handleClose">取消</el-button>
					<el-button type="primary" @click="submitCart" :disabled="cartItems.length === 0" :loading="state.submitting">
						<el-icon><Check /></el-icon>
						提交{{ cartType === 'inbound' ? '入库' : '出库' }}申请
					</el-button>
				</div>
			</div>
		</template>
	</el-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit, Check, ShoppingCart } from '@element-plus/icons-vue';
import { getAPI } from '/@/utils/axios-utils';
import { SysUserApi } from '/@/api-services/api';
import { useUserInfo } from '/@/stores/userInfo';

interface CartItem {
	id: number;
	storeTypeId: number;
	storeTypeDisplayName: string;
	name: string;
	price: number;
	unit: string;
	availableStock: number;
	requestQuantity: number;
	// 每项的接收信息
	receiverId?: number;
	receiverName?: string;
	receiverDept?: string;
	expectedDate?: string;
	statusNewOrChange?: number;
	remark?: string;
}

interface User {
	id: number;
	realName: string;
	orgName?: string;
	posName?: string;
}

interface SubmitForm {
	confirmerId?: number | null;
	confirmerName?: string | null;
}

const props = defineProps<{
	cartType: 'inbound' | 'outbound'; // 购物车类型：入库或出库
	cartItems: CartItem[];
}>();

const emit = defineEmits<{
	'submit-cart': [items: CartItem[], form: SubmitForm];
	'remove-item': [index: number];
	'clear-cart': [];
	close: [];
}>();

const submitFormRef = ref();
const userOptions = ref<User[]>([]);
const userInfo = useUserInfo(); // 获取用户信息

const state = reactive({
	visible: false,
	submitting: false,
	confirmerReadonly: true, // 确认人字段默认只读
	// 全局设置表单
	globalForm: {
		receiverId: null as number | null,
		receiverName: '',
		receiverDept: '',
		expectedDate: '',
		statusNewOrChange: props.cartType === 'inbound' ? 1 : 2, // 入库默认新增(1)，出库默认更新(2)
		remark: '',
		confirmerId: null as number | null, // 确认人ID
		confirmerName: '', // 确认人姓名
	},
});

// 购物车标题
const cartTitle = computed(() => {
	return props.cartType === 'inbound' ? '入库申请购物车' : '出库申请购物车';
});

// 计算总数量
const totalQuantity = computed(() => {
	return props.cartItems.reduce((total, item) => total + item.requestQuantity, 0);
});

// 计算总金额
const totalAmount = computed(() => {
	return props.cartItems.reduce((total: number, item: any) => total + item.price * item.requestQuantity, 0);
});

// 页面加载时获取用户列表
onMounted(async () => {
	await loadUserOptions();
});

// 加载用户选项（从用户列表获取）
const loadUserOptions = async () => {
	try {
		const params = {
			page: 1,
			pageSize: 100,
			status: 1, // 只获取启用的用户
			orgId: -1, // 所有组织
		};
		const result = await getAPI(SysUserApi).apiSysUserPagePost(params);
		userOptions.value = (result.data.result?.items || []).map((user: any) => ({
			id: user.id || 0,
			realName: user.realName || '',
			orgName: user.orgName || '',
			posName: user.posName || '',
		}));
	} catch (error) {
		console.error('加载用户列表失败:', error);
		ElMessage.error('加载用户列表失败');
		// 如果API失败，使用模拟数据
		userOptions.value = [
			{ id: 1, realName: '张三', orgName: '生产部', posName: '生产一组' },
			{ id: 2, realName: '李四', orgName: '仓储部', posName: '仓储管理员' },
			{ id: 3, realName: '王五', orgName: '质检部', posName: '质量控制员' },
			{ id: 4, realName: '赵六', orgName: '生产部', posName: '生产二组' },
			{ id: 5, realName: '钱七', orgName: '仓储部', posName: '物料管理员' },
		];
	}
};

// 处理全局接收人变化
const handleGlobalReceiverChange = (userId: number) => {
	const selectedUser = userOptions.value.find((user) => user.id === userId);
	if (selectedUser) {
		state.globalForm.receiverId = userId;
		state.globalForm.receiverName = selectedUser.realName;
		state.globalForm.receiverDept = selectedUser.orgName || '';
	}
};

// 处理单个项目接收人变化
const handleItemReceiverChange = (item: CartItem, userId: number) => {
	const selectedUser = userOptions.value.find((user) => user.id === userId);
	if (selectedUser) {
		item.receiverId = userId;
		item.receiverName = selectedUser.realName;
		item.receiverDept = selectedUser.orgName || '';
	}
};

// 处理确认人变化
const handleConfirmerChange = (userId: number) => {
	const selectedUser = userOptions.value.find((user) => user.id === userId);
	if (selectedUser) {
		state.globalForm.confirmerId = userId;
		state.globalForm.confirmerName = selectedUser.realName;
	}
};

// 切换确认人只读状态
const toggleConfirmerReadonly = () => {
	state.confirmerReadonly = !state.confirmerReadonly;
	if (state.confirmerReadonly) {
		ElMessage.success('确认人已锁定为只读');
	} else {
		ElMessage.info('确认人已解锁，可以编辑');
	}
};

// 打开购物车
const openCart = async () => {
	// 重置全局表单默认值
	state.globalForm.statusNewOrChange = props.cartType === 'inbound' ? 1 : 2;

	// 确保用户列表已加载
	if (userOptions.value.length === 0) {
		await loadUserOptions();
	}

	// 确认人可空，不再自动设置直属主管

	state.visible = true;
};

// 关闭购物车
const handleClose = () => {
	state.visible = false;
	emit('close');
};

// 移除物品
const removeFromCart = (index: number) => {
	emit('remove-item', index);
};

// 清空购物车
const clearCart = () => {
	ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		emit('clear-cart');
	});
};

// 更新物品小计
const updateItemTotal = (item: CartItem) => {
	// 确保数量在有效范围内
	if (item.requestQuantity < 1) {
		item.requestQuantity = 1;
	}
	// 只有出库时才检查库存上限
	if (props.cartType === 'outbound' && item.requestQuantity > item.availableStock) {
		item.requestQuantity = item.availableStock;
		ElMessage.warning(`申请数量不能超过可用库存 ${item.availableStock}`);
	}
};

// 应用全局设置
const applyGlobalSettings = () => {
	// 检查必填字段
	if (!state.globalForm.receiverId || !state.globalForm.expectedDate) {
		ElMessage.warning('请先选择接收人和预期时间');
		return;
	}

	ElMessageBox.confirm('此操作将覆盖所有物资的接收信息设置，确定要继续吗？', '应用全局设置', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		props.cartItems.forEach((item) => {
			Object.assign(item, {
				receiverId: state.globalForm.receiverId,
				receiverName: state.globalForm.receiverName,
				receiverDept: state.globalForm.receiverDept,
				expectedDate: state.globalForm.expectedDate,
				statusNewOrChange: state.globalForm.statusNewOrChange,
				remark: state.globalForm.remark,
			});
		});
		ElMessage.success('全局设置已应用到所有物资');
	});
};

// 提交购物车
const submitCart = async () => {
	try {
		if (props.cartItems.length === 0) {
			ElMessage.warning('购物车为空，请先添加物资');
			return;
		}

		// 检查申请数量
		const invalidItem = props.cartItems.find((item) => {
			if (item.requestQuantity <= 0) return true;
			// 只有出库时才检查数量是否超过可用库存
			if (props.cartType === 'outbound' && item.requestQuantity > item.availableStock) return true;
			return false;
		});
		if (invalidItem) {
			ElMessage.warning(`物资"${invalidItem.name}"的申请数量不正确`);
			return;
		}

		// 检查必填的接收信息
		const itemsWithoutReceiver = props.cartItems.filter((item) => !item.receiverId || !item.expectedDate);
		if (itemsWithoutReceiver.length > 0) {
			ElMessage.warning('请为所有物资设置接收人和预期时间');
			return;
		}

		state.submitting = true;
		emit('submit-cart', props.cartItems, {
			confirmerId: state.globalForm.confirmerId,
			confirmerName: state.globalForm.confirmerName,
		});
	} catch (error) {
		console.error('提交失败:', error);
		state.submitting = false;
	}
};

// 重置提交状态
const resetSubmitting = () => {
	state.submitting = false;
};

// 重置表单
const resetForm = () => {
	state.globalForm = {
		receiverId: null,
		receiverName: '',
		receiverDept: '',
		expectedDate: '',
		statusNewOrChange: props.cartType === 'inbound' ? 1 : 2,
		remark: '',
		confirmerId: null,
		confirmerName: '',
	};
	state.confirmerReadonly = true; // 重置时恢复只读状态
};

// 暴露方法
defineExpose({
	openCart,
	handleClose,
	resetSubmitting,
	resetForm,
});

// 监听购物车类型变化，重置默认状态
watch(
	() => props.cartType,
	(newType) => {
		state.globalForm.statusNewOrChange = newType === 'inbound' ? 1 : 2;
	}
);
</script>

<style scoped>
.cart-content {
	padding: 16px;
	height: calc(100vh - 140px);
	overflow-y: auto;
}

.price-text {
	color: #409eff;
	font-weight: 500;
}

.total-price {
	color: #e6a23c;
	font-weight: 600;
}

.cart-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16px;
	border-top: 1px solid #e4e7ed;
	background-color: #fafafa;
}

.footer-summary {
	font-size: 14px;
	color: #606266;
	font-weight: 500;
}

.footer-actions {
	display: flex;
	gap: 12px;
}

:deep(.el-drawer__body) {
	padding: 0;
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

:deep(.el-table) {
	font-size: 13px;
}

:deep(.el-table th) {
	background-color: #f8f9fa;
	color: #606266;
	font-weight: 600;
}

:deep(.el-input-number) {
	width: 100px;
}

:deep(.el-button--small) {
	padding: 5px 8px;
}

.confirmer-input-wrapper {
	display: flex;
	gap: 8px;
	align-items: stretch;
	width: 100%;
}

.confirmer-select {
	flex: 1;
	min-width: 0;
}

.confirmer-toggle-btn {
	flex-shrink: 0;
	white-space: nowrap;
}
</style>
